<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :disabled="isDetail"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="题库" prop="bankId">
        <el-select v-model="formData.bankId" placeholder="请选择题库">
          <el-option
            v-for="item in bankList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="章节" prop="chapter">
        <el-select v-model="formData.chapter" placeholder="请选择章节">
          <el-option label="请选择字典生成" value=""/>
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_QUESTION_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label=" 阅卷类型" prop="markType">
            <el-select v-model="formData.markType" placeholder="请选择 阅卷类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_MARK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label=" 阅卷选项" prop="markOptions">
            <el-select v-model="formData.markOptions" placeholder="请选择 阅卷选项">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.EXAM_MARK_OPTIONS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="状态" prop="state">
            <el-select
              v-model="formData.state"
              placeholder="请选择 状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="难度" prop="difficulty">
            <el-select v-model="formData.difficulty" placeholder="请选择难度">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_DIFFICULTY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="默认分值" prop="score">
            <el-input v-model="formData.score" placeholder="请输入默认分值"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="题干" prop="title">
        <el-input type="textarea" v-model="formData.title" placeholder="请输入题干" autosize/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor v-model="formData.content" height="150px"/>
      </el-form-item>
      <el-form-item label="解析" prop="analysis">
        <Editor v-model="formData.analysis" height="150px"/>
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="试题选项" name="questionOption">
        <QuestionOptionForm ref="questionOptionFormRef" :question-id="formData.id" :is-detail="isDetail"/>
      </el-tab-pane>
      <el-tab-pane label="试题答案" name="questionAnswer">
        <QuestionAnswerForm ref="questionAnswerFormRef" :question-id="formData.id" :is-detail="isDetail"/>
      </el-tab-pane>
      <el-tab-pane label="知识点" name="questionLabel">
        <QuestionLabelForm ref="questionLabelFormRef" :question-id="formData.id" :label="formData.label" :is-detail="isDetail"/>
      </el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script setup lang="ts">
import {getIntDictOptions, getStrDictOptions, DICT_TYPE} from '@/utils/dict'
import {QuestionApi, QuestionVO} from '@/api/exam/question'
import QuestionAnswerForm from '@/views/exam/components/QuestionAnswerForm.vue'
import QuestionOptionForm from '@/views/exam/components/QuestionOptionForm.vue'
import QuestionLabelForm from '@/views/exam/components/QuestionLabelForm.vue'
import {BankApi, BankVO} from "@/api/exam/bank";
import {useTagsViewStore} from "@/store/modules/tagsView";

/** 试题 表单 */
defineOptions({name: 'QuestionForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  bankId: undefined,
  type: undefined,
  title: undefined,
  content: undefined,
  markType: undefined,
  markOptions: undefined,
  analysis: undefined,
  score: undefined,
  state: undefined,
  difficulty: undefined,
  chapter: undefined,
  label: undefined
})
const formRules = reactive({
  bankId: [{required: true, message: '题库不能为空', trigger: 'change'}],
  type: [{required: true, message: '类型不能为空', trigger: 'change'}],
  title: [{required: true, message: '题干不能为空', trigger: 'blur'}],
  markType: [{required: true, message: ' 阅卷类型不能为空', trigger: 'change'}],
  markOptions: [{required: true, message: ' 阅卷选项不能为空', trigger: 'change'}],
  score: [{required: true, message: '默认分值不能为空', trigger: 'blur'}],
  state: [{required: true, message: '状态不能为空', trigger: 'blur'}],
  difficulty: [{required: true, message: '难度不能为空', trigger: 'change'}],
  chapter: [{required: false, message: '章节不能为空', trigger: 'change'}],
  label: [{required: true, message: '知识点不能为空', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('questionAnswer')
const questionAnswerFormRef = ref()
const questionOptionFormRef = ref()
const questionLabelFormRef = ref()
const isDetail = ref(false) // 是否查看详情
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时或者查询时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await QuestionApi.getQuestion(id)
      if (formData.value.analysis === undefined) {
        formData.value.analysis = "";
      }
      if (formData.value.content === undefined) {
        formData.value.content = "";
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await questionAnswerFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'questionAnswer'
    return
  }
  try {
    await questionOptionFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'questionOption'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as QuestionVO
    // 拼接子表的数据
    data.questionAnswers = questionAnswerFormRef.value.getData()
    data.questionOptions = questionOptionFormRef.value.getData()
    data.questionLabels = questionLabelFormRef.value.getData()
    if(data.questionLabels){
      const labels = []
      data.questionLabels.forEach(label =>{
        labels.push(label.name);
      })
      data.label = labels.join(',');
    }
    if (formType.value === 'create') {
      await QuestionApi.createQuestion(data)
      message.success(t('common.createSuccess'))
    } else {
      await QuestionApi.updateQuestion(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    bankId: undefined,
    type: undefined,
    title: undefined,
    content: undefined,
    markType: undefined,
    markOptions: undefined,
    analysis: undefined,
    score: undefined,
    state: undefined,
    difficulty: undefined,
    chapter: undefined,
    label: undefined
  }
  formRef.value?.resetFields()
}
const bankList = ref<BankVO[]>([]) // 列表的数据

const getBankList = async () => {
  try {
    const data = await BankApi.getBankPage({})
    bankList.value = data.list
  } finally {
  }
}
/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'Question' })
}

/** 初始化 **/
onMounted(async () => {
  await getBankList();
  const id = params.id as unknown as number
  if ('QuestionEdit' === name) {
    await open('update', id)
  }else if ('QuestionAdd' === name) {
    await open('create', id)
  } else if ('QuestionDetail' === name) {
    await open('detail', id)
    isDetail.value = true;
  }

})
</script>
